<template>
  <div class="goods-edit-container">
    <el-card class="edit-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑商品' : '创建商品' }}</span>
          <el-button-group>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
          </el-button-group>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="goods-form"
      >
        <!-- 基本信息 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-header">
              <span>基本信息</span>
              <el-tag type="info" size="small">必填</el-tag>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入商品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品分类" prop="categoryIds">
                <el-cascader
                  v-model="formData.categoryIds"
                  :options="categoryOptions"
                  :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                  placeholder="请选择商品分类"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品类型" prop="type">
                <el-select v-model="formData.type" placeholder="请选择商品类型">
                  <el-option
                    v-for="(label, value) in GOODS_TYPE"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品标签" prop="tags">
                <el-select
                  v-model="formData.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入商品标签"
                >
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品主图" prop="mainImage">
            <el-upload
              class="main-image-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :on-success="handleMainImageSuccess"
              :on-error="handleUploadError"
            >
              <img v-if="formData.mainImage" :src="formData.mainImage" class="main-image" />
              <el-icon v-else class="main-image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议尺寸：800x800px，支持 jpg、png 格式</div>
          </el-form-item>

          <el-form-item label="商品图片" prop="images">
            <el-upload
              v-model:file-list="imageList"
              :action="uploadUrl"
              :headers="uploadHeaders"
              list-type="picture-card"
              :before-upload="beforeImageUpload"
              :on-success="handleImageSuccess"
              :on-error="handleUploadError"
              :on-remove="handleImageRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">最多上传 9 张图片，建议尺寸：800x800px</div>
          </el-form-item>

          <el-form-item label="商品简介" prop="brief">
            <el-input
              v-model="formData.brief"
              type="textarea"
              :rows="3"
              placeholder="请输入商品简介"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-card>

        <!-- 规格参数 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-header">
              <span>规格参数</span>
              <el-tag type="info" size="small">必填</el-tag>
            </div>
          </template>

          <el-form-item label="规格类型" prop="specType">
            <el-radio-group v-model="formData.specType">
              <el-radio :label="SPEC_TYPE.SINGLE">单规格</el-radio>
              <el-radio :label="SPEC_TYPE.MULTI">多规格</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 单规格 -->
          <template v-if="formData.specType === SPEC_TYPE.SINGLE">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="销售价" prop="price">
                  <el-input-number
                    v-model="formData.price"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    placeholder="请输入销售价"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="市场价" prop="originalPrice">
                  <el-input-number
                    v-model="formData.originalPrice"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    placeholder="请输入市场价"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="库存" prop="stock">
                  <el-input-number
                    v-model="formData.stock"
                    :min="0"
                    :step="1"
                    placeholder="请输入库存"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- 多规格 -->
          <template v-else>
            <el-form-item label="规格模板" prop="specTemplateId">
              <el-select
                v-model="formData.specTemplateId"
                placeholder="请选择规格模板"
                @change="handleSpecTemplateChange"
              >
                <el-option
                  v-for="template in specTemplates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id"
                />
              </el-select>
              <el-button type="primary" link @click="handleCreateSpecTemplate">
                新建规格模板
              </el-button>
            </el-form-item>

            <el-form-item label="规格列表" prop="specs">
              <div class="spec-list">
                <div v-for="(spec, index) in formData.specs" :key="index" class="spec-item">
                  <el-row :gutter="20">
                    <el-col :span="6">
                      <el-form-item
                        :label="'规格' + (index + 1)"
                        :prop="'specs.' + index + '.name'"
                        :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }"
                      >
                        <el-input v-model="spec.name" placeholder="规格名称" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="规格值"
                        :prop="'specs.' + index + '.values'"
                        :rules="{ required: true, message: '请输入规格值', trigger: 'blur' }"
                      >
                        <el-select
                          v-model="spec.values"
                          multiple
                          filterable
                          allow-create
                          default-first-option
                          placeholder="请选择或输入规格值"
                        >
                          <el-option
                            v-for="value in spec.valueOptions"
                            :key="value"
                            :label="value"
                            :value="value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-button type="danger" link @click="removeSpec(index)">
                        删除规格
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-button type="primary" link @click="addSpec">添加规格</el-button>
              </div>

              <el-table
                v-if="formData.specs.length"
                :data="specCombinations"
                border
                style="width: 100%; margin-top: 20px"
              >
                <el-table-column
                  v-for="spec in formData.specs"
                  :key="spec.name"
                  :label="spec.name"
                  :prop="spec.name"
                />
                <el-table-column label="销售价" width="180">
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.price"
                      :min="0"
                      :precision="2"
                      :step="0.1"
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="市场价" width="180">
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.originalPrice"
                      :min="0"
                      :precision="2"
                      :step="0.1"
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="库存" width="180">
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.stock"
                      :min="0"
                      :step="1"
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="商品编码" width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.code" size="small" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>
        </el-card>

        <!-- 商品详情 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-header">
              <span>商品详情</span>
              <el-tag type="info" size="small">必填</el-tag>
            </div>
          </template>

          <el-form-item label="商品详情" prop="detail">
            <el-tabs v-model="detailTab">
              <el-tab-pane label="富文本编辑" name="rich">
                <div class="editor-container">
                  <el-toolbar-editor
                    v-model="formData.detail"
                    :min-height="400"
                    :upload-url="uploadUrl"
                    :upload-headers="uploadHeaders"
                  />
                </div>
              </el-tab-pane>
              <el-tab-pane label="HTML源码" name="html">
                <el-input
                  v-model="formData.detail"
                  type="textarea"
                  :rows="20"
                  placeholder="请输入HTML源码"
                />
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-header">
              <span>其他信息</span>
              <el-tag type="info" size="small">选填</el-tag>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运费模板" prop="logisticsTemplateId">
                <el-select
                  v-model="formData.logisticsTemplateId"
                  placeholder="请选择运费模板"
                >
                  <el-option
                    v-for="template in logisticsTemplates"
                    :key="template.id"
                    :label="template.name"
                    :value="template.id"
                  />
                </el-select>
                <el-button type="primary" link @click="handleCreateLogisticsTemplate">
                  新建运费模板
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品单位" prop="unit">
                <el-input v-model="formData.unit" placeholder="请输入商品单位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品重量" prop="weight">
                <el-input-number
                  v-model="formData.weight"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  placeholder="请输入商品重量"
                />
                <span class="unit-text">kg</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品体积" prop="volume">
                <el-input-number
                  v-model="formData.volume"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  placeholder="请输入商品体积"
                />
                <span class="unit-text">m³</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入商品备注"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-card>
      </el-form>
    </el-card>

    <!-- 规格模板对话框 -->
    <el-dialog
      v-model="specTemplateDialogVisible"
      title="新建规格模板"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="specTemplateFormRef"
        :model="specTemplateForm"
        :rules="specTemplateRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="specTemplateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="规格列表" prop="specs">
          <div class="spec-list">
            <div v-for="(spec, index) in specTemplateForm.specs" :key="index" class="spec-item">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item
                    :label="'规格' + (index + 1)"
                    :prop="'specs.' + index + '.name'"
                    :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }"
                  >
                    <el-input v-model="spec.name" placeholder="规格名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="规格值"
                    :prop="'specs.' + index + '.values'"
                    :rules="{ required: true, message: '请输入规格值', trigger: 'blur' }"
                  >
                    <el-select
                      v-model="spec.values"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="请选择或输入规格值"
                    >
                      <el-option
                        v-for="value in spec.valueOptions"
                        :key="value"
                        :label="value"
                        :value="value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" link @click="removeTemplateSpec(index)">
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" link @click="addTemplateSpec">添加规格</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="specTemplateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSpecTemplate" :loading="savingTemplate">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 运费模板对话框 -->
    <el-dialog
      v-model="logisticsTemplateDialogVisible"
      title="新建运费模板"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="logisticsTemplateFormRef"
        :model="logisticsTemplateForm"
        :rules="logisticsTemplateRules"
        label-width="120px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="logisticsTemplateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="计费方式" prop="type">
          <el-radio-group v-model="logisticsTemplateForm.type">
            <el-radio :label="1">按件数</el-radio>
            <el-radio :label="2">按重量</el-radio>
            <el-radio :label="3">按体积</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域" prop="regions">
          <el-table :data="logisticsTemplateForm.regions" border style="width: 100%">
            <el-table-column label="配送区域" min-width="300">
              <template #default="scope">
                <el-cascader
                  v-model="scope.row.regionIds"
                  :options="regionOptions"
                  :props="{ multiple: true, value: 'id', label: 'name' }"
                  placeholder="请选择配送区域"
                />
              </template>
            </el-table-column>
            <el-table-column label="首件/重/体积" width="180">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.first"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="首费" width="180">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.firstFee"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="续件/重/体积" width="180">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.additional"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="续费" width="180">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.additionalFee"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click="removeLogisticsRegion(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-2">
            <el-button type="primary" link @click="addLogisticsRegion">
              添加配送区域
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="logisticsTemplateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveLogisticsTemplate" :loading="savingTemplate">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  GOODS_TYPE,
  SPEC_TYPE,
  getGoodsDetail,
  createGoods,
  updateGoods,
  getGoodsCategories,
  getSpecTemplates,
  createSpecTemplate,
  getLogisticsTemplates,
  createLogisticsTemplate
} from '@/api/goods'

const route = useRoute()
const router = useRouter()
const isEdit = computed(() => !!route.params.id)

// 加载状态
const loading = ref(false)
const saving = ref(false)
const savingTemplate = ref(false)

// 表单数据
const formRef = ref(null)
const formData = reactive({
  name: '',
  categoryIds: [],
  type: '',
  tags: [],
  mainImage: '',
  images: [],
  brief: '',
  specType: SPEC_TYPE.SINGLE,
  price: null,
  originalPrice: null,
  stock: null,
  specTemplateId: null,
  specs: [],
  detail: '',
  logisticsTemplateId: null,
  unit: '',
  weight: null,
  volume: null,
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryIds: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  type: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
  mainImage: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
  images: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  brief: [{ required: true, message: '请输入商品简介', trigger: 'blur' }],
  specType: [{ required: true, message: '请选择规格类型', trigger: 'change' }],
  price: [{ required: true, message: '请输入销售价', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  detail: [{ required: true, message: '请输入商品详情', trigger: 'blur' }]
}

// 图片上传
const uploadUrl = '/api/merchant/upload'
const uploadHeaders = {
  // 设置上传请求头
}
const imageList = ref([])

// 商品分类
const categoryOptions = ref([])

// 规格模板
const specTemplates = ref([])
const specTemplateDialogVisible = ref(false)
const specTemplateFormRef = ref(null)
const specTemplateForm = reactive({
  name: '',
  specs: []
})

// 运费模板
const logisticsTemplates = ref([])
const logisticsTemplateDialogVisible = ref(false)
const logisticsTemplateFormRef = ref(null)
const logisticsTemplateForm = reactive({
  name: '',
  type: 1,
  regions: []
})

// 地区选项
const regionOptions = ref([])

// 详情编辑器
const detailTab = ref('rich')

// 获取商品详情
const fetchGoodsDetail = async (id) => {
  loading.value = true
  try {
    const { data } = await getGoodsDetail(id)
    Object.assign(formData, data)
    // 处理图片列表
    imageList.value = data.images.map(url => ({
      url,
      name: url.split('/').pop()
    }))
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 获取商品分类
const fetchCategories = async () => {
  try {
    const { data } = await getGoodsCategories()
    categoryOptions.value = data
  } catch (error) {
    console.error('获取商品分类失败:', error)
    ElMessage.error('获取商品分类失败')
  }
}

// 获取规格模板
const fetchSpecTemplates = async () => {
  try {
    const { data } = await getSpecTemplates()
    specTemplates.value = data
  } catch (error) {
    console.error('获取规格模板失败:', error)
    ElMessage.error('获取规格模板失败')
  }
}

// 获取运费模板
const fetchLogisticsTemplates = async () => {
  try {
    const { data } = await getLogisticsTemplates()
    logisticsTemplates.value = data
  } catch (error) {
    console.error('获取运费模板失败:', error)
    ElMessage.error('获取运费模板失败')
  }
}

// 保存商品
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    const data = {
      ...formData,
      images: imageList.value.map(item => item.url)
    }
    
    if (isEdit.value) {
      await updateGoods(route.params.id, data)
      ElMessage.success('更新成功')
    } else {
      await createGoods(data)
      ElMessage.success('创建成功')
    }
    
    router.push('/goods')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存商品失败:', error)
      ElMessage.error('保存商品失败')
    }
  } finally {
    saving.value = false
  }
}

// 取消
const handleCancel = () => {
  ElMessageBox.confirm('确定要离开吗？未保存的内容将会丢失', '提示', {
    type: 'warning'
  }).then(() => {
    router.back()
  }).catch(() => {})
}

// 图片上传相关
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const handleMainImageSuccess = (response) => {
  formData.mainImage = response.url
}

const handleImageSuccess = (response, file) => {
  file.url = response.url
}

const handleImageRemove = (file) => {
  const index = imageList.value.indexOf(file)
  if (index !== -1) {
    imageList.value.splice(index, 1)
  }
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 规格相关
const handleSpecTemplateChange = (templateId) => {
  const template = specTemplates.value.find(t => t.id === templateId)
  if (template) {
    formData.specs = template.specs.map(spec => ({
      ...spec,
      values: []
    }))
  }
}

const addSpec = () => {
  formData.specs.push({
    name: '',
    values: [],
    valueOptions: []
  })
}

const removeSpec = (index) => {
  formData.specs.splice(index, 1)
}

// 规格组合
const specCombinations = computed(() => {
  if (!formData.specs.length) return []
  
  const combinations = []
  const generateCombinations = (specs, current = {}, index = 0) => {
    if (index === specs.length) {
      combinations.push({
        ...current,
        price: null,
        originalPrice: null,
        stock: null,
        code: ''
      })
      return
    }
    
    const spec = specs[index]
    spec.values.forEach(value => {
      generateCombinations(specs, { ...current, [spec.name]: value }, index + 1)
    })
  }
  
  generateCombinations(formData.specs)
  return combinations
})

// 规格模板相关
const handleCreateSpecTemplate = () => {
  specTemplateForm.name = ''
  specTemplateForm.specs = []
  specTemplateDialogVisible.value = true
}

const addTemplateSpec = () => {
  specTemplateForm.specs.push({
    name: '',
    values: [],
    valueOptions: []
  })
}

const removeTemplateSpec = (index) => {
  specTemplateForm.specs.splice(index, 1)
}

const saveSpecTemplate = async () => {
  if (!specTemplateFormRef.value) return
  
  try {
    await specTemplateFormRef.value.validate()
    savingTemplate.value = true
    
    const { data } = await createSpecTemplate(specTemplateForm)
    specTemplates.value.push(data)
    formData.specTemplateId = data.id
    specTemplateDialogVisible.value = false
    
    ElMessage.success('创建成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存规格模板失败:', error)
      ElMessage.error('保存规格模板失败')
    }
  } finally {
    savingTemplate.value = false
  }
}

// 运费模板相关
const handleCreateLogisticsTemplate = () => {
  logisticsTemplateForm.name = ''
  logisticsTemplateForm.type = 1
  logisticsTemplateForm.regions = []
  logisticsTemplateDialogVisible.value = true
}

const addLogisticsRegion = () => {
  logisticsTemplateForm.regions.push({
    regionIds: [],
    first: 1,
    firstFee: 0,
    additional: 1,
    additionalFee: 0
  })
}

const removeLogisticsRegion = (index) => {
  logisticsTemplateForm.regions.splice(index, 1)
}

const saveLogisticsTemplate = async () => {
  if (!logisticsTemplateFormRef.value) return
  
  try {
    await logisticsTemplateFormRef.value.validate()
    savingTemplate.value = true
    
    const { data } = await createLogisticsTemplate(logisticsTemplateForm)
    logisticsTemplates.value.push(data)
    formData.logisticsTemplateId = data.id
    logisticsTemplateDialogVisible.value = false
    
    ElMessage.success('创建成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存运费模板失败:', error)
      ElMessage.error('保存运费模板失败')
    }
  } finally {
    savingTemplate.value = false
  }
}

// 初始化
onMounted(async () => {
  await Promise.all([
    fetchCategories(),
    fetchSpecTemplates(),
    fetchLogisticsTemplates()
  ])
  
  if (isEdit.value) {
    await fetchGoodsDetail(route.params.id)
  }
})
</script>

<style scoped>
.goods-edit-container {
  padding: 20px;
}

.edit-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.main-image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.main-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.main-image {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
}

.spec-list {
  .spec-item {
    margin-bottom: 16px;
    padding: 16px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.mt-2 {
  margin-top: 8px;
}

/* 响应式布局优化 */
@media screen and (max-width: 1400px) {
  .el-col-12 {
    width: 100%;
  }
  
  .el-col-8 {
    width: 50%;
  }
}

@media screen and (max-width: 768px) {
  .el-col-8 {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    gap: 16px;
  }
}
</style> 